package com.xinggq.common;

import com.xinggq.common.enums.ResponseEnum;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

/**
 * 响应数据对象
 *
 * @param <T> 范型
 * @author zhangyajun
 * @since 2023/9/20 09:46
 */
@Data
@Accessors(chain = true)
@NoArgsConstructor
public class CommonResult<T> {

  /**
   * 响应码
   */
  protected Integer code;

  /**
   * 响应信息
   */
  protected String msg;

  /**
   * 数据集
   */
  protected T data;

  /* Constructors */

  public CommonResult(ResponseEnum responseEnum) {
    this.code = responseEnum.getCode();
    this.msg = responseEnum.getMsg();
  }

  public CommonResult(Integer code, String msg) {
    this.code = code;
    this.msg = msg;
  }

  /* Build Methods */

  public static <A> CommonResult<A> ok() {
    return new CommonResult<>(ResponseEnum.SUCCESS);
  }

  public static <A> CommonResult<A> ok(A data) {
    return new CommonResult<A>(ResponseEnum.SUCCESS).setData(data);
  }


  public static <A> CommonResult<A> fail() {
    return new CommonResult<>(ResponseEnum.REQUEST_FAIL);
  }

  public static <A> CommonResult<A> fail(String msg) {
    return new CommonResult<>(ResponseEnum.REQUEST_FAIL.getCode(), msg);

  }

  public static <A> CommonResult<A> fail(ResponseEnum responseEnum) {
    return new CommonResult<>(responseEnum);
  }

  public static <A> CommonResult<A> result(ResponseEnum responseEnum) {
    return new CommonResult<>(responseEnum);
  }


  public static <A> CommonResult<A> result(Integer code, String msg) {
    return new CommonResult<>(code, msg);
  }

  public static CommonResult<Void> authFail(String msg) {
    return new CommonResult<>(ResponseEnum.AUTH_FAILURE.getCode(), msg);
  }

  /**
   * 判断当前结果是否成功
   *
   * @return 当 code 等于 SUCCESS(1000) 时返回 true
   */
  public boolean isSuccess() {
    return this.code != null && this.code.equals(ResponseEnum.SUCCESS.getCode());
  }
}